<template>
  <el-dialog v-if="openForm" v-model="openBoole" title="选择产品" :close-on-click-modal="false" custom-class="mydialog"
    width="60%" @close="close">
    <el-form ref="openRef" :model="openForm" :rules="rules" size="small">
      <el-row gutter="40">

        <el-col :span="24">
          <el-form-item label="产品线" style="width: 100%">
            <el-select v-model="openForm.productLine" style="width: 100%" placeholder="产品线" @change="listSearch">
              <el-option label="全部" :value="0" />
              <el-option v-for="(itm) in productLineOptions" :key="itm.id" :label="itm.productLineName"
                :value="itm.id" />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item style="width: 100%" props="tableData">
            <el-table ref="multipleTable" v-table="tableLoadMore" :data="openForm.tableData"
              header-cell-class-name="table-header" size="medium" height="300" border :row-key="handlRowKey"
              @selection-change="handleSelectionChange">
              <el-table-column type="selection" :reserve-selection="true" width="55" />

              <el-table-column prop="productPopularName" :min-width="160" label="产品通用名" header-align="center"
                :show-overflow-tooltip="true" />

              <el-table-column prop="productName" :min-width="160" label="商品名" header-align="center"
                :show-overflow-tooltip="true" />

              <el-table-column prop="producer" :min-width="160" label="生产厂家" header-align="center"
                :show-overflow-tooltip="true" />

              <el-table-column prop="packSpecs" :min-width="160" label="包装规格" header-align="center"
                :show-overflow-tooltip="true" />

              <el-table-column prop="approvalNumber" :min-width="160" label="批准文号" header-align="center"
                :show-overflow-tooltip="true" />

              <el-table-column :min-width="160" label="所属产品线" header-align="center" :show-overflow-tooltip="true">
                <template #default="scope">
                  <span> {{ scope.row.productLineDetail?.productLineName }}</span>
                </template>
              </el-table-column>

            </el-table>
          </el-form-item>
          <!-- <Pagination v-model:page="openForm.page" v-model:limit="openForm.pageSize"
            style="display: flex; justify-content: flex-end" :total="total" @pagination="handlList" /> -->
        </el-col>

      </el-row>
    </el-form>

    <template #footer>
      <div class="dialog-footer" style="display:flex;justify-content:center;align-items:center;">
        <el-button class="border-btn" size="small" style="margin-right: 20px;" @click="close">取消</el-button>

        <el-button class="main-btn" size="small" type="primary" @click="handlSubmit">添加</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import { getCurrentInstance, inject, onMounted, reactive, toRefs } from "vue";
import { crmStore } from "@CRM/store";

export default {
  name: "Product",
  setup(props, context) {
    const validateTable = (rule, value, callback) => {
      if (data.multipleSelection.length === 0) {
        callback(new Error("请至少选择一个产品"));
      } else {
        callback();
      }
    };
    const currentInstance = getCurrentInstance();
    const api = inject("api");
    const data = reactive({
      openForm: {
        productLine: 0,
        pageSize: 20,
        page: 1,
        tableData: [],
      },
      region: [],
      openRef: null,
      terminalData: crmStore.getters["dictionary/getDictionary"]["app_mode"],
      total: 0,
      openBoole: false,
      multipleSelection: [],
      rules: {
        tableData: [
          { validator: validateTable, tyep: "array", trigger: "change" },
        ],
      },
      multipleTable: null,
      productLineOptions: [],
    });

    const getProductLine = () => {
      api.system.PRODUCTLINE_LIST().then((res) => {
        if (res.code === 0) {
          data.productLineOptions = res.data.list;
        }
      });
    };

    const listSearch = () => {
      handlList();
    };

    const close = () => {
      data.openBoole = false;
      data.openRef.clearValidate();
      data.openRef.resetFields();
      data.multipleSelection = [];
    };

    const open = (val) => {
      data.multipleSelection = JSON.parse(JSON.stringify(val));
      data.multipleTable?.clearSelection();
      console.log(data.multipleSelection, "-----------");
      handlList();
      data.openBoole = true;
    };

    const toggleSelection = (rows) => {
      // data.multipleTable.clearSelection();
      if (rows) {
        rows.forEach((row) => {
          data.multipleTable.toggleRowSelection(row, undefined);
        });
      }
    };

    // 获取列表
    const handlList = () => {
      api.terminal.TERMINAL_LIST_PRODUCT(data.openForm).then((res) => {
        if (res.code === 0) {
          if (data.openForm.page == 1) {
            data.openForm.tableData = res.data.list || [];
          } else {
            data.openForm.tableData = data.openForm.tableData.concat(
              res.data.list
            );
          }
          data.total = res.data.total;
        }
      });
    };

    const tableLoadMore = () => {
      if (data.openForm.tableData.length < data.total) {
        data.openForm.page++;
        handlList();
      } else {
        currentInstance.proxy.customMessage({
          type: "warning",
          message: "数据已到底了",
        });
      }
    };

    const handlRowKey = (row) => {
      return row.id || row.productId;
    };

    const handleSelectionChange = (val) => {
      let arr = [];
      val.forEach((item) => {
        let a = currentInstance.proxy.getProductName(item);
        arr.push({
          productName: a,
          productId: item?.id,
          ifSelect: true,
        });
      });
      arr = handlUnique(arr, "productId");
      data.multipleSelection = arr.filter((a) => a.productId !== undefined);
    };

    const handlSubmit = () => {
      data.openRef.validate((valid) => {
        if (valid) {
          context.emit("succsessProduct", data.multipleSelection);
          close();
        }
      });
    };

    const handlUnique = (arr, id) => {
      const res = new Map();
      return arr.filter((arr) => !res.has(arr[id]) && res.set(arr[id], 1));
    };

    onMounted(() => {
      getProductLine();
      handlList();
    });

    return {
      ...toRefs(data),
      getProductLine,
      close,
      open,
      handlList,
      handlRowKey,
      handleSelectionChange,
      handlSubmit,
      toggleSelection,
      listSearch,
      handlUnique,
      tableLoadMore,
    };
  },
};
</script>

<style scoped>
/* @import url(); 引入css类 */
</style>
